using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace eeZeeFTP
{
    public partial class FormLogin : Form
    {
        private string sUsername = "";
        private string sPassword = "";
        private string sHost = "";
        private int iPort = 21;

        private string sInitialPath = "";

        public string Username
        {
            get { return sUsername; }
            set { sUsername = value; }
        }

        public string Password
        {
            get { return sPassword; }
            set { sPassword = value; }
        }

        public int Port
        {
            get { return iPort; }
            set { iPort = value; }
        }

        public string Host
        {
            get { return sHost; }
            set 
            {
                //2002:579b:27f3:0:3411:de76:5a02:98b
                if(value.StartsWith("["))
                {
                    value = value.Substring(1, value.LastIndexOf("]"));

                    if (value.LastIndexOf(":") > value.LastIndexOf("]"))
                        Port = Convert.ToInt32(value.Substring(value.LastIndexOf(":") + 1));
                }
                else if(value.Contains(":"))
                {
                    string[] aParts = value.Split(':');
                    sHost = aParts[0];

                    if (aParts.Length == 1)
                    {
                        try
                        {
                            Port = Convert.ToInt32(aParts[1]);
                        }
                        catch 
                        {
                            Port = 21;
                        }
                    }
                    else
                        sHost = value; 
                }
                else
                    sHost = value; 
            }
        }
       
        public FormLogin()
        {
            InitializeComponent();
        }

        public void addNewConnection(string sUrl)
        {
            this.tB_Host.Text = sUrl;

            if (cB_User.Text == "")
                cB_User.SelectedItem = "anonymous";

            btnLoginOk_Click(btnLoginOk, EventArgs.Empty);
        }

        private void loadHostList()
        {
            try
            {
                lV_Hosts.Items.Clear();

                Microsoft.Win32.RegistryKey OurKey = Microsoft.Win32.Registry.CurrentUser;
                OurKey = OurKey.OpenSubKey("SOFTWARE", true);
                Microsoft.Win32.RegistryKey settings = OurKey.OpenSubKey(ProductName + @"\Hosts", true);

                if (settings == null)
                {
                    OurKey.CreateSubKey(ProductName);
                    OurKey.CreateSubKey(ProductName + @"\Hosts");

                    settings = OurKey.OpenSubKey(ProductName + @"\Hosts", true);
                }

                string[] sKeys = settings.GetSubKeyNames();

                foreach (string s in sKeys)
                {
                    Microsoft.Win32.RegistryKey HostKey = OurKey.OpenSubKey(ProductName + @"\Hosts\" + s, true);

                    ListViewItem lvi = new ListViewItem();

                    lvi.Text = s;

                    lvi.SubItems.Add(HostKey.GetValue("Server").ToString()); 

                    lvi.SubItems.Add(HostKey.GetValue("User").ToString());

                    lvi.SubItems.Add(HostKey.GetValue("Password").ToString());

                    lvi.SubItems.Add(HostKey.GetValue("Port").ToString());

                    lV_Hosts.Items.Add(lvi);
                }

                lV_Hosts.Sort();
            }
            catch { }
        }

        public void saveHost()
        {
            try
            {
                Microsoft.Win32.RegistryKey OurKey = Microsoft.Win32.Registry.CurrentUser;
                OurKey = OurKey.OpenSubKey("SOFTWARE", true);
                Microsoft.Win32.RegistryKey settings = OurKey.OpenSubKey(ProductName + @"\Hosts", true);

                if (settings == null)
                {
                    OurKey.CreateSubKey(ProductName);
                    OurKey.CreateSubKey(ProductName + @"\Hosts");

                    settings = OurKey.OpenSubKey(ProductName + @"\Hosts", true);
                }

                Microsoft.Win32.RegistryKey host = OurKey.OpenSubKey(ProductName + @"\Hosts\" + this.Username + "@" + this.Host + ":" + this.Port, true);

                if (host == null)
                {
                    host = OurKey.CreateSubKey(ProductName + @"\Hosts\" + this.Username + "@" + this.Host + ":" + this.Port);
                }

                host.SetValue("Server", this.Host);
                host.SetValue("User", this.Username);
                host.SetValue("Password", this.Password);
                host.SetValue("Port", this.Port.ToString());
            }
            catch { }
        }

        private void btnLoginCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void btnLoginOk_Click(object sender, EventArgs e)
        {
            this.Username = cB_User.Text;
            this.Password = tBLoginPass.Text;
            this.Host = tB_Host.Text;
            
            //saveHost();

            this.DialogResult = DialogResult.OK;
        }

        private void FormLogin_Load(object sender, EventArgs e)
        {
            //if (lV_Hosts.Items.Count > 0) return;

            loadHostList();

            //if (lV_Hosts.Items.Count > 0)
            //    lV_Hosts.Items[0].Selected = true;

            tB_Host.Select();
        }

        private void lV_Hosts_KeyUp(object sender, KeyEventArgs e)
        {
            if (lV_Hosts.SelectedItems.Count == 0) return;

            if (e.KeyData == Keys.Delete)
            {
                Microsoft.Win32.RegistryKey OurKey = Microsoft.Win32.Registry.CurrentUser;
                OurKey = OurKey.OpenSubKey("SOFTWARE", true);
                Microsoft.Win32.RegistryKey settings = OurKey.OpenSubKey(ProductName + @"\Hosts", true);

                if (settings != null)
                {
                    OurKey.DeleteSubKey(ProductName + @"\Hosts\" + lV_Hosts.SelectedItems[0].Text);
                    lV_Hosts.SelectedItems[0].Remove();
                }
            }
        }

        private void lV_Hosts_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(lV_Hosts.SelectedItems.Count == 0) return;

            tB_Host.Text = lV_Hosts.SelectedItems[0].SubItems[1].Text;

            cB_User.Text = lV_Hosts.SelectedItems[0].SubItems[2].Text;

            tBLoginPass.Text = lV_Hosts.SelectedItems[0].SubItems[3].Text;

            tB_Host.Text += ":" + lV_Hosts.SelectedItems[0].SubItems[4].Text;
        }

        private void cB_User_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cB_User.SelectedItem.ToString().ToLower() == "anonymous")
                tBLoginPass.Text = "anonymous@anonymous.net";
        }

        private void lV_Hosts_DoubleClick(object sender, EventArgs e)
        {
            if (lV_Hosts.SelectedItems.Count == 0) return;

            btnLoginOk_Click(btnLoginOk, EventArgs.Empty);
        }

        private void tB_Host_TextChanged(object sender, EventArgs e)
        {
            if(tB_Host.Text.ToLower().StartsWith("ftp://"))
            {
                string s = tB_Host.Text.Substring(6);

                string[] aParts = s.Split('@');

                if (aParts.Length > 1)
                {
                    string[] aPartsUser = aParts[0].Split(':');

                    cB_User.Text = aPartsUser[0];

                    if (aPartsUser.Length > 1)
                        tBLoginPass.Text = aPartsUser[1];
                    else
                        tBLoginPass.Text = "";

                    s = aParts[1];
                }
                else
                    cB_User.SelectedItem = "anonymous";

                if (s.IndexOf('/') > 0)
                {
                    tB_Host.Text = s.Substring(0, s.IndexOf('/'));
                    sInitialPath = s.Substring(s.IndexOf('/'));
                }
                else
                    tB_Host.Text = s;
            }
        }

        public string getInitialPath(Encoding e, int CodePage)
        {
            string sRet = System.Web.HttpUtility.UrlDecode(sInitialPath, Encoding.GetEncoding(CodePage));
            sInitialPath = "";

            byte[] bytes = Encoding.GetEncoding(CodePage).GetBytes(sRet);

            return e.GetString(Encoding.Convert(Encoding.GetEncoding(CodePage), e, bytes));
        }
    }
}